<script>
import { io } from "socket.io-client";

export default {
  data() {
    return {
      timer: "",
      counter: 0,
      imgSrc: "/assets/logo.png",
    };
  },
  mounted() {
    setInterval(() => {
      this.counter++;
    }, 1000);

    const socket = io(
      "http://127.0.0.1:4000", //'ws://127.0.0.1:3000'
      {
        path: "/socket.io", // socket.io 库默认服务端path为/socket.io
        transports: ["websocket", "xhr-polling", "jsonp-polling"], //此配置在我的代码中表现为必须项，官方示例未列出，请指教
      }
    );
    socket.on("connect", (res) => {
      console.log("#connect: ", res);

      //发送信息给服务端
      socket.emit("login", {
        username: "username",
        password: "password",
      });

      //接收服务端的信息
      socket.on("sendShareScreen", (data) => {
        // console.log(base64Img);
        this.imgSrc = "data:image/png;base64," + this.arrayBufferToBase64(data);
      });

      this.timer = setInterval(function () {
        socket.emit("getShareScreen", {});
      }, 50);
    });
    socket.on("message", (res) => {
      console.log("#message: ", res);
    });
    socket.on("disconnect", () => {
      console.log("断开连接");
    });
  },
  methods: {
    arrayBufferToBase64(buffer) {
      var binary = "";
      var bytes = new Uint8Array(buffer);
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return window.btoa(binary);
    },
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<template>
  <div>
    Counter: {{ counter }}
    <img alt="Vue" :src="imgSrc" />
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
